from flask import request, json
from flask_cors import CORS
import requests
from is_valid import is_valid 
from model import User, Userinfo, create_app, db
from werkzeug.security import check_password_hash


app = create_app()
app.app_context().push()
db.create_all()
CORS(app)

@app.route('/login', methods=["POST", "GET"])
def login():
    if request.method == "POST":
        # 解析数据
        data = request.get_json()
        data = json.loads(data)
        username = data['username']
        passwd = data['password']

        # 防SQL注入
        if (not (is_valid(username) and is_valid(passwd))):
            return {
                "status": 0,
                "message": "Illegal parameters"
            }

        user = User.query.filter_by(username= username).first()
        if(user and check_password_hash(user.password, passwd)):
            userinfo = user.userinfo
            return {
                "status": 1,
                "message": "Login Successful!",
                "uid": userinfo.id,
                "name": userinfo.name,
                "studentID": userinfo.studentid,
                "gender": userinfo.gender
            }
            # r = requests.post('http://jwt:5000/create-token', data= {'userid': user.id})
            # access_token = r.json().get("access_token")
            # userinfo = user.userinfo
            # if(r.status_code == 200):
            #     return {
            #         "status": 1,
            #         "message": "Login Successful!",
            #         "access_token": access_token,
            #         "name": userinfo.name,
            #         "studentID": userinfo.studentid,
            #         "gender": userinfo.gender
            # }
            # else:
            #     return {
            #         "status": 0,
            #         "message": "Error token"
            #     }

        else:
            return {
                "status": 0,
                "message": "Incorrect username or password!"
            }
            


if __name__ == "__main__":
    app.run(host = '0.0.0.0')